package com.gao.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gao.dao.OrderDao;
import com.gao.domain.Order;
import com.gao.domain.User;
import com.gao.util.DBUtil;

public class OrderDaoImpl implements OrderDao{

	@Override
	public boolean insert(Order order) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "insert into orders values(?,?,'δ����',?,now())";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1,order.getOid());
		pstmt.setInt(2, order.getUser().getUid());
		pstmt.setDouble(3, order.getAmount());
		//ʱ���ö���
		//pstmt.setObject(3, LocalDateTime.now());
		int num = pstmt.executeUpdate();
		DBUtil.release(pstmt, conn);
		return num>0;
	}

	@Override
	public boolean updateNumber(String oid, String newState) throws SQLException {
		// TODO Auto-generated method stub
		Connection conn = DBUtil.getConnection();
		String sql = "update orders set state=? where oid=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, newState);
		pstmt.setString(2, oid);
		int num = pstmt.executeUpdate();
		DBUtil.release(pstmt, conn);
		return num>0;
	}

	@Override
	public List<Order> getOrdersByUid(int uid) throws SQLException {
		List<Order> orders = new ArrayList<Order>();
		Order order = null;
		Connection conn = DBUtil.getConnection();
		String sql = "select * from orders where uid=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1,uid);
		ResultSet rs = pstmt.executeQuery();
		while(rs.next()){
			order = new Order(rs.getString(1),new User(uid),rs.getString(3),rs.getDouble(4),rs.getTimestamp(5));
			orders.add(order);
			System.out.println(order);
			
		}
		DBUtil.release(rs,pstmt, conn);
		return orders;
	}
	

	@Override
	public String getStateByOid(String oid) throws SQLException {
		String state = null;
		Connection conn = DBUtil.getConnection();
		String sql = "select state from orders where oid=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1,oid);
		ResultSet rs = pstmt.executeQuery();
		if(rs.next()){
			state = rs.getString(1);
		}
		DBUtil.release(rs,pstmt, conn);
		return state;
	}
}
